package com.jinzhi.jzweb.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.domain.DictDO;
import com.jinzhi.common.service.DictService;
import com.jinzhi.common.utils.Result;
import com.jinzhi.jzapi.msg.PackTemplateMap;
import com.jinzhi.jzapi.msg.WxPushServiceQcl;
import com.jinzhi.jzapi.msg.domain.TemplateData;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.sys.domain.RoleDO;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.domain.UserRoleDO;
import com.jinzhi.sys.service.RoleService;
import com.jinzhi.sys.service.UserRoleService;
import com.jinzhi.sys.service.UserService;
import com.jinzhi.wxmp.domain.MpConfigDO;
import com.jinzhi.wxmp.service.MpConfigService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 
 * <pre>
 * 专家表
 * </pre>
 * <small> 2020-02-24 21:00:11 | lance</small>
 */
@Controller
@RequestMapping("/jzweb/experts")
public class ExpertsController extends BaseController {
	@Autowired
	private ExpertsService expertsService;
	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private UserRoleService userRoleService;
	@Autowired
	private KnowledgePointsService knowledgePointsService;
	@Autowired
	private CertificateProfileService certificateProfileService;
	@Autowired
	private OrganizationNewsService organizationNewsService;
	@Autowired
	private CertificateNewsService certificateNewsService;
	@Autowired
	private DictService dictService;
	@Autowired
	private MsgService msgService;
	@Autowired
	private MsgTemplateService msgTemplateService;
	@Autowired
	private WxPushServiceQcl wxPushServiceQcl;
	@Autowired
	private MpConfigService mpConfigService;

	@GetMapping()
	@RequiresPermissions("jzweb:experts:experts")
	String Experts(){
	    return "jzweb/experts/experts";
	}
	
	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("jzweb:experts:experts")
	public Result<Page<ExpertsDO>> list(ExpertsDO expertsDTO){

		String roleName = "";
		List<UserRoleDO> userRole = userRoleService.findByKv("userId", this.getUserId());
		if(userRole != null && userRole.size() > 0){
			for(UserRoleDO roleDO : userRole){
				RoleDO role = roleService.selectById(roleDO.getRoleId());
				roleName = roleName + role.getRoleName() + ",";
			}
		}
		Wrapper<ExpertsDO> wrapper = null;
		if (roleName.indexOf("普通用户,资讯发布,") != -1){
			wrapper = new EntityWrapper<ExpertsDO>().orderBy("id", false);
		}
		if (roleName.indexOf("超级用户角色") == -1) {
			wrapper = new EntityWrapper<ExpertsDO>().orderBy("id", false);
			wrapper.eq("org_id" , this.getUser().getOrgId());
			if (roleName.indexOf("培训机构") != -1 && roleName.indexOf("考核站点") != -1){

			}else {
				if (roleName.indexOf("考核站点") != -1){
					wrapper.notIn("type" , 4);//除了讲师以外的所有类型专家
				}
				if (roleName.indexOf("培训机构") != -1){
					wrapper.eq("type" , 4);
				}

				if (roleName.indexOf("普通用户,资讯发布,") != -1){
					wrapper = new EntityWrapper<ExpertsDO>().orderBy("id", false);
				}
			}

		}else {
			wrapper = new EntityWrapper<ExpertsDO>().orderBy("id", false);
		}
		if (expertsDTO.getState() != null){
			wrapper.eq("state",expertsDTO.getState());
		}
		if (expertsDTO.getType() != null){
			wrapper.eq("type",expertsDTO.getType());
		}
		if (expertsDTO.getName() != null){
			wrapper.like("name",expertsDTO.getName());
		}
		if (StringUtils.isNotBlank(expertsDTO.getProfileName())){
			Wrapper<CertificateProfileDO> cerWrapper = new EntityWrapper<CertificateProfileDO>().like("name",expertsDTO.getProfileName());
			List<CertificateProfileDO>  certificateProfileDOS = certificateProfileService.selectList(cerWrapper);
			String str = "";
			for (CertificateProfileDO certificateProfileDO : certificateProfileDOS){
				str = str + certificateProfileDO.getId() + ",";
			}
			wrapper.and();
			if(StringUtils.isNotBlank(str)){
				wrapper.in("profile_id",str.substring(0,str.length()-1));
			}else{
				wrapper.eq("profile_id",null);
			}
		}
		if (StringUtils.isNotBlank(expertsDTO.getKpointsName())){
			Wrapper<KnowledgePointsDO> knWrapper = new EntityWrapper<KnowledgePointsDO>().like("name",expertsDTO.getKpointsName()).and().eq("pid",0);
			List<KnowledgePointsDO>  knowledgePointsDOS = knowledgePointsService.selectList(knWrapper);
			String str = "";
			for (KnowledgePointsDO knowledgePointsDO : knowledgePointsDOS){
				str = str + knowledgePointsDO.getId() + ",";
			}
			wrapper.and();
			if(StringUtils.isNotBlank(str)){
				wrapper.in("kpoints_id",str.substring(0,str.length()-1));
			}else{
				wrapper.eq("kpoints_id",null);
			}
		}
		if (StringUtils.isNotBlank(expertsDTO.getOrgName())){
			Wrapper<OrganizationNewsDO> orWrapper = new EntityWrapper<OrganizationNewsDO>().like("name",expertsDTO.getOrgName());
			List<OrganizationNewsDO>  organizationNewsDOS = organizationNewsService.selectList(orWrapper);
			String str = "";
			for (OrganizationNewsDO organizationNewsDO : organizationNewsDOS){
				str = str + organizationNewsDO.getId() + ",";
			}
			wrapper.and();
			if(StringUtils.isNotBlank(str)){
				wrapper.in("org_id",str.substring(0,str.length()-1));
			}else{
				wrapper.eq("org_id",null);
			}
		}

		Page<ExpertsDO> page = expertsService.selectPage(getPage(ExpertsDO.class), wrapper);
		List list = new ArrayList();
		for (int i = 0; i < page	.getRecords().size(); i++) {
			ExpertsDO obj = (ExpertsDO) page.getRecords().get(i);
			if (obj.getKpointsId() != null) {
				KnowledgePointsDO knowledgePointsDO = knowledgePointsService.selectById(obj.getKpointsId());
				if (knowledgePointsDO != null) {
					obj.setKpointsName(knowledgePointsDO.getName());
				}
			}
			//如专家表机构id为空，则不展示
			if (obj.getOrgId() != null){
				OrganizationNewsDO organizationNewsDO = organizationNewsService.selectById(obj.getOrgId());
				if (organizationNewsDO != null) {
					obj.setOrgName(organizationNewsDO.getName());
				}
			}
			if (obj.getProfileId() != null){
				CertificateProfileDO certificateProfileDO = certificateProfileService.selectById(obj.getProfileId());
				if (certificateProfileDO != null) {
					obj.setProfileName(certificateProfileDO.getName());
				}
			}
			if (obj.getCheckerId() != null){
				UserDO userDO = userService.selectById(obj.getCheckerId());
				if (userDO != null) {
					obj.setCheckerName(userDO.getUsername());
				}
			}
			list.add(obj);
		}
		page.setRecords(list);
        return Result.ok(page);
	}
	
	@GetMapping("/add")
	@RequiresPermissions("jzweb:experts:add")
	String add(Model model){
//		model.addAttribute("orgNews",organizationNewsService.selByOrgId());
		//查询pid
		model.addAttribute("certificateProfile",certificateNewsService.selByProfile());
	    return "jzweb/experts/add";
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("jzweb:experts:edit")
	String edit(@PathVariable("id") Long id,Model model){
//		model.addAttribute("orgNews",organizationNewsService.selByOrgId());
		model.addAttribute("certificateProfile",certificateNewsService.selByProfile());
		ExpertsDO experts = expertsService.selectById(id);
		model.addAttribute("experts", experts);
	    return "jzweb/experts/edit";
	}

	@GetMapping("/info")
	@RequiresPermissions("jzweb:experts:experts")
	String info(Model model,Long id, Long uid) {
		UserDO userDO = userService.selectById(uid);
		ExpertsDO experts = expertsService.selectById(id);
		userDO.setHonor(experts.getHonor());
		model.addAttribute("user", userDO);
		return "jzweb/experts/info";
	}
	
	@Log("添加专家表")
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("jzweb:experts:add")
	public Result<String> save( ExpertsDO experts){
		ExpertsDO expertsDO = expertsService.findOneByKv("user_id",experts.getUserId(),"type",experts.getType());
		if(expertsDO == null){
			if (experts.getUserId() != null){
				UserDO userDO = userService.selectById(experts.getUserId());
				if (userDO != null) {
					experts.setName(userDO.getName());
					if(userDO.getOrgId() == null){
						return Result.fail("该用户用户表所属机构信息为空，请添加后重试！！");
					}else{
						experts.setOrgId(userDO.getOrgId());
					}
				}
			}
			experts.setApplicantDate(new Date());
			expertsService.insert(experts);
		}else{
			return Result.fail("专家已存在，请勿重复添加！");
		}

        return Result.ok();
	}
	
	@Log("修改专家表")
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("jzweb:experts:edit")
	public Result<String>  update( ExpertsDO experts){
		//根据题目内容、课程id、章节id、题目类型判断是否重复
		List<ExpertsDO> expertsDOs = expertsService.findByKv("user_id",experts.getUserId(),"type",experts.getType());
		if (expertsDOs != null && expertsDOs.size() > 0) {
			if (expertsDOs.size() == 1) {
				if (expertsDOs.get(0).getId().equals(experts.getId())) {
					if (experts.getUserId() != null){
						UserDO userDO = userService.selectById(experts.getUserId());
						if (userDO != null) {
							experts.setName(userDO.getName());
							if(userDO.getOrgId() == null && experts.getOrgId() != null){
								OrganizationNewsDO organizationNewsDO = organizationNewsService.selectById(experts.getOrgId());
								userDO.setOrgId(organizationNewsDO.getId());
								userDO.setOrgName(organizationNewsDO.getName());
								userService.updateById(userDO);
							}
						}
					}
					experts.setState(0);//修改了专家信息之后，状态改为未审核；需要重新再审核一次；
					ExpertsDO oldExpertsDO = expertsService.selectById(experts.getId());
					//删除原本的角色权限，重新审核后赋权；
					delRoleExp(oldExpertsDO.getType(),oldExpertsDO.getUserId());
					boolean update = expertsService.updateById(experts);
					return update ? Result.ok() : Result.fail();
				}
			}
			return Result.fail("专家已存在，请勿重复添加！");
		} else {
			if (experts.getUserId() != null){
				UserDO userDO = userService.selectById(experts.getUserId());
				if (userDO != null) {
					experts.setName(userDO.getName());
					if(userDO.getOrgId() == null && experts.getOrgId() != null){
						OrganizationNewsDO organizationNewsDO = organizationNewsService.selectById(experts.getOrgId());
						userDO.setOrgId(organizationNewsDO.getId());
						userDO.setOrgName(organizationNewsDO.getName());
						userService.updateById(userDO);
					}
				}
			}
			experts.setState(0);//修改了专家信息之后，状态改为未审核；需要重新再审核一次；
			ExpertsDO oldExpertsDO = expertsService.selectById(experts.getId());
			//删除原本的角色权限，重新审核后赋权；
			delRoleExp(oldExpertsDO.getType(),oldExpertsDO.getUserId());
			boolean update = expertsService.updateById(experts);
			return update ? Result.ok() : Result.fail();
		}
	}
	
	@Log("删除专家表")
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("jzweb:experts:remove")
	public Result<String>  remove( Long id){
		ExpertsDO oldExpertsDO = expertsService.selectById(id);
		//删除原本的角色权限，重新审核后赋权；
		delRoleExp(oldExpertsDO.getType(),oldExpertsDO.getUserId());
		expertsService.deleteById(id);
        return Result.ok();
	}
	
	@Log("批量删除专家表")
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("jzweb:experts:batchRemove")
	public Result<String>  remove(@RequestParam("ids[]") Long[] ids){
		for(Long id : ids){
			ExpertsDO oldExpertsDO = expertsService.selectById(id);
			//删除原本的角色权限，重新审核后赋权；
			delRoleExp(oldExpertsDO.getType(),oldExpertsDO.getUserId());
		}

		expertsService.deleteBatchIds(Arrays.asList(ids));
		return Result.ok();
	}

	boolean delRoleExp(Integer type,Long userId) {
		boolean b = true;
		//给会员赋予相应角色权限
		String roleNames = null;
		if (type.equals(0)) {
			roleNames = "考评员";
		} else if (type.equals(1)) {
			roleNames = "考务员";
		} else if (type.equals(2)) {
			roleNames = "考务技术员";
		} else if (type.equals(3)) {
			roleNames = "督导员";
		} else if(type.equals(4)){
			roleNames = "讲师";
		}
		if (roleNames != null) {
			RoleDO roleDO = roleService.findOneByKv("roleName", roleNames);

			//查询用户角色
			UserRoleDO userRole = userRoleService.findOneByKv("userId", userId,"roleId",roleDO.getId());
			if(userRole != null){
				b = userRoleService.deleteById(userRole.getId());
			}
		}

		return b;
	}

	@Log("审核")
	@PostMapping( "/review")
	@ResponseBody
	@RequiresPermissions("jzweb:experts:review")
	public Result<String>  review(@RequestParam("ids[]") Long[] ids,Integer state,String remark){
		if (state.equals(2) || state.equals(1)) {

			//查询字典:消息模板
			DictDO dic = null;
			String valStr = "";
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			if (state == 2){
				dic = dictService.findOneByKv("type" , "check_no_pass");
				valStr = dic.getValue().replace("{value4}" , remark);
			}else {
				dic = dictService.findOneByKv("type" , "check_pass");
				valStr = dic.getValue();
			}
			valStr =  valStr.replace("{value1}" , "专家信息");
			valStr = valStr.replace("{value2}" , this.getUser().getUsername());
			valStr = valStr.replace("{value3}" , formatter.format(new Date()));

			int i = 0;
			boolean ccbb = true;
			String exName = "";
			for (Long id : ids) {
				ExpertsDO expertsDO = expertsService.selectById(id);
				if(expertsDO != null){
					if(expertsDO.getState()==6){
						return Result.fail("请勿选择草稿数据");
					}
					MsgDO msg = new MsgDO();
					if(expertsDO.getOrgId() == null){
						ccbb = false;
						if(exName.equals("")){
							exName = exName + expertsDO.getName();
						}else{
							exName = exName + "," + expertsDO.getName();
						}
					}else{
						expertsDO.setState(state);
						expertsDO.setCheckerId(this.getUserId());
						expertsDO.setCheckerDate(new Date());
						if(state.equals(2)){
							expertsDO.setRemark(remark);//未通过，添加备注
							msg.setTitle("专家信息审核未通过！");
						}else{
							expertsDO.setRemark("");//审核通过，清空备注
							msg.setTitle("专家信息审核通过！");
						}

						boolean b = expertsService.updateById(expertsDO);
						if (b) {

							msg.setContent(valStr);
							msg.setUserId(expertsDO.getUserId());
							msg.setCreaterDate(new Date());
//						msg.setEnclosure();
							msg.setType(0);
							msg.setMsgType(0);
							msg.setState(0);
							msg.setCreaterId(this.getUserId());
							msgService.insert(msg);

							//------------------------订阅消息模块-----------------------------\
							UserDO user = userService.selectById(expertsDO.getUserId());
							MsgTemplateDO msgTemplate = msgTemplateService.findOneByKv("type" , 0, "temp_ip" ,101);
							if (user.getCerOpenId() != null){
								if (msgTemplate != null){
									String[] value = null;
									MsgTemplateDO templateDO = null;
									if (state == 1){//通过
										templateDO = msgTemplateService.findOneByKv("pid" , msgTemplate.getId() , "type" , 2 , "temp_ip" , 101);
										if (templateDO != null){
											value = templateDO.getContent().split("/n");
											for (int a = 0; a < value.length; a++){
												value[a] = value[a].replace("{value1}" ,"专家");
												value[a] = value[a].replace("{value2}" ,"专家");
												value[a] = value[a].replace("{date}" , formatter.format(new Date()));
											}
										}
									}else if (state == 2){//未通过
										templateDO = msgTemplateService.findOneByKv("pid" , msgTemplate.getId() , "type" , 3, "temp_ip" , 101);
										if (templateDO != null){
											value = templateDO.getContent().split("/n");
											for (int a = 0; a < value.length; a++){
												value[a] = value[a].replace("{value1}" ,"专家");
												value[a] = value[a].replace("{value2}" ,"专家");
												value[a] = value[a].replace("{remark}" ,remark);
												value[a] = value[a].replace("{date}" , formatter.format(new Date()));
											}
										}
									}
									if (templateDO != null){
										String[] parm = msgTemplate.getContent().split(",");
										Map<String, TemplateData> map = PackTemplateMap.get1(value , parm);

										MpConfigDO mc = mpConfigService.selectById(101);
										wxPushServiceQcl.sendMsgToUser(mc.getId().intValue() ,user.getCerOpenId(),msgTemplate.getCode(),map ,"pages/proRecord/proRecord");
									}
								}
							}
							//------------------------订阅消息模块结束-----------------------------\
							if(state.equals(1)){
								//给会员赋予相应角色权限
								String roleNames = null;
								if(expertsDO.getType().equals(0)){
									roleNames = "考评员";
								}else if(expertsDO.getType().equals(1)){
									roleNames = "考务员";
								}else if(expertsDO.getType().equals(2)){
									roleNames = "考务技术员";
								}else if(expertsDO.getType().equals(3)){
									roleNames = "督导员";
								}else if(expertsDO.getType().equals(4)){
									roleNames = "讲师";
								}
								if(roleNames != null){
									RoleDO roleDO = roleService.findOneByKv("roleName",roleNames);

									List<RoleDO> roleDOS = roleService.findListByUserId(expertsDO.getUserId());
									if(roleDOS != null && roleDOS.size() > 0){
										List<String> roleNamess = new ArrayList<>();
										for(RoleDO roleDO1:roleDOS){
											roleNamess.add(roleDO1.getRoleName());
										}
										//当前列表若包含该角色，返回结果为true, 若不包含该角色，返回结果为false。
										if (!(roleNamess.indexOf(roleNames) > -1)) {

											if(roleDO != null){
												UserRoleDO userRoleDO = new UserRoleDO();
												userRoleDO.setUserId(expertsDO.getUserId());
												userRoleDO.setRoleId(roleDO.getId());
												boolean c = userRoleService.insert(userRoleDO);
												if(!c){
													i--;
												}
											}
										}
									}else{
										if(roleDO != null){
											UserRoleDO userRoleDO = new UserRoleDO();
											userRoleDO.setUserId(expertsDO.getUserId());
											userRoleDO.setRoleId(roleDO.getId());
											boolean c = userRoleService.insert(userRoleDO);
											if(!c){
												i--;
											}
										}
									}
								}
							}

							i++;
						} else {
							break;
						}
					}
				}
			}

			if(!ccbb){
				return Result.fail("请先给专家:" + exName + "添加所属机构！其他专家已完成审核");
			}

			if (i == ids.length) {
				return Result.build(0,"已成功审核：" + i + "条数据");
			} else {
				return Result.fail("审核状态修改失败！");
			}
		} else {
			return Result.fail("审核状态修改失败！");
		}
	}
	
}
